package com.tim.app.ui.activity.setting;

import android.app.Activity;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.SmoothSwitchScreenUtil;
import com.application.library.util.StringUtil;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.WindowUtils;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.SignRequestParams;
import com.tim.app.server.result.GetValidationCodeResult;
import com.tim.app.server.result.LoginResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 绑定手机
 */
public class BindMobileOrResetPasswordActivity extends BaseActivity {

    private static final String TAG = "BindMobileOrResetPasswordActivity";

    private EditText input_phone_num, input_sms_mark, et_input_password;
    private TextView show_time;
    private CountDownTimer timer;
    private boolean isTiming = false;
    private String phone, smscode;
    private Button btConfrim;
    private TextView tvTitle;

    private int type;
    private String platformUid;
    private String accessToken;
    private int platformType;
    private User thirdAuthUser;
    private ImageView ivPassword;

    public static void startBindMobileOrResetPasswordActivity(Activity context, User user, int platformType, int type, String platformUid, String accessToken, int requestCode) {
        Intent intent = new Intent(context, BindMobileOrResetPasswordActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("platformType", platformType);
        intent.putExtra("platformUid", platformUid);
        intent.putExtra("accessToken", accessToken);
        if (null != user) {
            intent.putExtra("thirdAuthUser", user);
        }
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onBeforeSetContentLayout() {
        super.onBeforeSetContentLayout();
        SmoothSwitchScreenUtil.smoothSwitchScreen(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reset_password;
    }

    @Override
    public void initView() {
        input_phone_num = (EditText) findViewById(R.id.et_input_phone_num);
        input_sms_mark = (EditText) findViewById(R.id.register_input_sms_mark);
        et_input_password = (EditText) findViewById(R.id.et_input_password);
        show_time = (TextView) findViewById(R.id.register_get_sms_mark_tx);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        input_phone_num.addTextChangedListener(new MyEditChangeListener());
        input_sms_mark.addTextChangedListener(new MyEditChangeListener());
        et_input_password.addTextChangedListener(new MyEditChangeListener());
        btConfrim = (Button) findViewById(R.id.btConfrim);
        ivPassword = (ImageView) findViewById(R.id.ivPassword);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.register_get_sms_mark_tx).setOnClickListener(this);
        btConfrim.setOnClickListener(this);
        ivPassword.setOnClickListener(this);
        timer = new CountDownTimer(AppKey.VERTIFY_SECONDS * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                show_time.setText(millisUntilFinished / 1000 + getString(R.string.txt_bind_resend));
            }

            @Override
            public void onFinish() {
                isTiming = false;
                show_time.setText(getString(R.string.get_sms_mark));
                show_time.setEnabled(true);
            }
        };
    }

    private class MyEditChangeListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (AppKey.TYPE_BING_MOBILE == type) {
                if (TextUtils.isEmpty(input_phone_num.getText().toString().trim()) || TextUtils.isEmpty(input_sms_mark.getText().toString().trim())) {
                    btConfrim.setEnabled(false);
                } else {
                    btConfrim.setEnabled(true);
                }
            } else if (AppKey.TYPE_FIND_WORD == type) {
                if (TextUtils.isEmpty(et_input_password.getText().toString().trim()) || TextUtils.isEmpty(input_phone_num.getText().toString().trim()) || TextUtils.isEmpty(input_sms_mark.getText().toString().trim())) {
                    btConfrim.setEnabled(false);
                } else {
                    btConfrim.setEnabled(true);
                }
            }
        }
    }

    @Override
    public void initData() {
        type = getIntent().getIntExtra("type", AppKey.TYPE_FIND_WORD);
        platformType = getIntent().getIntExtra("platformType", 0);
        platformUid = getIntent().getStringExtra("platformUid");
        accessToken = getIntent().getStringExtra("accessToken");
        if (getIntent().hasExtra("thirdAuthUser")) {
            thirdAuthUser = (User) getIntent().getSerializableExtra("thirdAuthUser");
        }
        if (AppKey.TYPE_FIND_WORD == type) {
            tvTitle.setText(getString(R.string.resetPassword));
            btConfrim.setText(getString(R.string.modtifyPasswordToLogin));
            findViewById(R.id.rlPasswordContainer).setVisibility(View.VISIBLE);
            findViewById(R.id.vLine).setVisibility(View.VISIBLE);
        } else if (type == AppKey.TYPE_BING_MOBILE) {
            tvTitle.setText(getString(R.string.bindMobile));
            btConfrim.setText(getString(R.string.bindMobileToLogin));
            findViewById(R.id.rlPasswordContainer).setVisibility(View.GONE);
            findViewById(R.id.vLine).setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btConfrim) {
            phone = input_phone_num.getText().toString();
            smscode = input_sms_mark.getText().toString();
            String password = et_input_password.getText().toString();
            if (AppKey.TYPE_BING_MOBILE == type) {
                bindMobile(smscode);
            } else if (AppKey.TYPE_FIND_WORD == type) {
                if (checkLogin(phone, password)) {
                    phoneLogin(phone, password);
                }
                resetPassword(phone, smscode, password);
            }
        } else if (v.getId() == R.id.iv_back) {
            finish();
        } else if (v.getId() == R.id.register_get_sms_mark_tx) {
            if (isTiming) {
                return;
            }
            phone = input_phone_num.getText().toString();
            if (TextUtils.isEmpty(phone)) {
                ToastUtil.showToast(RT.getString(R.string.input_phone_num));
                return;
            }
            if (!phone.matches(StringUtil.ZHENGZE_PHONE)) {
                ToastUtil.showToast(RT.getString(R.string.error_mobile_error));
                return;
            }
            getVerifyApi();
        } else if (v.getId() == R.id.ivPassword) {
            if (ivPassword.isSelected()) {
                ivPassword.setSelected(false);
                et_input_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                ivPassword.setSelected(true);
                et_input_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            et_input_password.postInvalidate();
            //切换后将EditText光标置于末尾
            CharSequence charSequence = et_input_password.getText();
            if (charSequence instanceof Spannable) {
                Spannable spanText = (Spannable) charSequence;
                Selection.setSelection(spanText, charSequence.length());
            }
        }
    }


    /**
     * 检测登陆参数
     *
     * @param phone
     * @param password
     * @return
     */
    public boolean checkLogin(String phone, String password) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_empty));
            return false;
        }
        if (!phone.matches(StringUtil.ZHENGZE_PHONE)) {
            ToastUtil.showToast(RT.getString(R.string.error_mobile_error));
            return false;
        }
        if (TextUtils.isEmpty(password) || !password.matches(StringUtil.ZHENGZE_PASSWORD)) {
            ToastUtil.showToast(RT.getString(R.string.error_password));
            return false;
        }
        return true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (input_phone_num != null) {
            SoftKeyboardUtil.hideSoftKeyboard(input_phone_num);
        }
        if (input_sms_mark != null) {
            SoftKeyboardUtil.hideSoftKeyboard(input_sms_mark);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null && isTiming) {
            timer.cancel();
        }
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    /**
     * 获取验证码
     */
    private void getVerifyApi() {
        showLoadingDialog();
        int verifyType = AppKey.TYPE_FIND_WORD;
        if (AppKey.TYPE_BING_MOBILE == type) {
            verifyType = AppKey.VERTIFY_BINDMOBILE;
        } else if (AppKey.TYPE_FIND_WORD == type) {
            verifyType = AppKey.VERTIFY_RESETPASSWORD;
        }
        API_User.ins().getPhoneVerificationCode(TAG, verifyType, phone, platformType, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean fromCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    show_time.setEnabled(false);
                    isTiming = true;
                    timer.start();
                    if (!TextUtils.isEmpty(resultValue)) {
                        GetValidationCodeResult result = new Gson().fromJson(resultValue, GetValidationCodeResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getPhoneauth())) {
                                input_sms_mark.setText(result.getRes().getHashmap().getPhoneauth());
                            }
                        }
                    }
                } else if (errCode == ResponseResult.ResultStatus.HAS_BIND) {
                    ToastUtil.showToast("该手机已经被绑定");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 绑定手机
     *
     * @param validationCode
     */
    private void bindMobile(final String validationCode) {
        showLoadingDialog();
        int verifyType = AppKey.TYPE_FIND_WORD;
        if (AppKey.TYPE_BING_MOBILE == type) {
            verifyType = AppKey.VERTIFY_BINDMOBILE;
        } else if (AppKey.TYPE_FIND_WORD == type) {
            verifyType = AppKey.VERTIFY_RESETPASSWORD;
        }
        API_User.ins().checkPhoneAuthCommon(TAG, verifyType, phone, validationCode, platformType, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean fromCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    if (!TextUtils.isEmpty(resultValue)) {
                        LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {

                            if (result.getRes().getHashmap().getPhoneState() == LoginResult.Res.Data.STATE_BIND_SUCCESS) {
                                if (null != result.getRes().getHashmap().getUser()) {
                                    UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                                    regist(validationCode);
                                }
                                if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                    UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                                }
                            } else if (result.getRes().getHashmap().getPhoneState() == LoginResult.Res.Data.STATE_UNBIND) {
                                regist(validationCode);
                            } else if (result.getRes().getHashmap().getPhoneState() == LoginResult.Res.Data.STATE_HAS_BIND) {
                                ToastUtil.showToast("该帐号已绑定手机号");
                            }
                        }

                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 绑定成功模拟注册
     *
     * @param validationCode
     */
    private void regist(String validationCode) {
        API_User.ins().regist(TAG, platformType, phone, SignRequestParams.MDString("moli2017"), validationCode, platformUid, accessToken, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                String type = "";
                if (platformType == AppKey.LOGIN_TYPE_SINA) {
                    type = "wb";
                } else if (platformType == AppKey.LOGIN_TYPE_QQ) {
                    type = "qq";
                } else if (platformType == AppKey.LOGIN_TYPE_WX) {
                    type = "wx";
                } else if (platformType == AppKey.LOGIN_TYPE_MOBILE) {
                    type = "phone";
                }
                if (errCode == ResponseResult.ResultStatus.OK) {
                    if (!TextUtils.isEmpty(resultValue)) {
                        LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);
                        if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                            if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                                PerfectPersonInfomationActivity.start(BindMobileOrResetPasswordActivity.this, result.getRes().getHashmap().getUser(), AppKey.LOGIN_TYPE_MOBILE, -1);
                            } else {
                                if (null != result.getRes().getHashmap().getUser()) {
                                    UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                                }
                                if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                    UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                                }
                                UserManager.ins().saveLoginType(type);
                                EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                                API_Statistics.ins().addRegistData(TAG, BindMobileOrResetPasswordActivity.this, type);
                                UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getUserId());
                                Intent intent = new Intent(BindMobileOrResetPasswordActivity.this, MainActivity.class);
                                startActivity(intent);
                                setResult(RESULT_OK);
                                finish();
                            }
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (AppKey.TYPE_THIRD_REGIST == requestCode) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    /**
     * 重置密码
     */
    private void resetPassword(final String phone, String validationCode, final String password) {
        showLoadingDialog();
        API_User.ins().resetPassword(TAG, phone, validationCode, SignRequestParams.MDString(password), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean fromCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    phoneLogin(phone, password);
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    /**
     * 手机登录
     *
     * @param phone
     * @param password
     */
    private void phoneLogin(final String phone, final String password) {
        showLoadingDialog();
        API_User.ins().loginByMobile(TAG, phone, SignRequestParams.MDString(password), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK && !TextUtils.isEmpty(resultValue)) {
                    LoginResult result = new Gson().fromJson(resultValue, LoginResult.class);

                    if (null != result && null != result.getRes() && null != result.getRes().getHashmap()) {
                        if (result.getRes().getHashmap().getIsPerfectInfo() == 1) {
                            PerfectPersonInfomationActivity.start(BindMobileOrResetPasswordActivity.this, result.getRes().getHashmap().getUser(), platformType, AppKey.TYPE_THIRD_REGIST);
                        } else {
                            if (null != result.getRes().getHashmap().getUser()) {
                                UserManager.ins().saveUserInfo(result.getRes().getHashmap().getUser());
                            }
                            if (!TextUtils.isEmpty(result.getRes().getHashmap().getAccessToken())) {
                                UserManager.ins().saveToken(result.getRes().getHashmap().getAccessToken());
                            }
                            UserManager.ins().saveLoginType("phone");
                            API_Statistics.ins().addLoginData(TAG, BindMobileOrResetPasswordActivity.this, "phone", phone);
                            UserManager.ins().loginChat(result.getRes().getHashmap().getUser().getUserId());
                            JPushInterface.setAlias(BindMobileOrResetPasswordActivity.this, UserManager.ins().getChatId(UserManager.ins().getUserId()), new TagAliasCallback() {
                                @Override
                                public void gotResult(int i, String s, Set<String> set) {

                                }
                            });
                            EventManager.ins().sendEvent(EventTag.ACCOUNT_LOGIN, 0, 0, null);
                        }

                        Intent intent = new Intent(BindMobileOrResetPasswordActivity.this, MainActivity.class);
                        startActivity(intent);
                        setResult(RESULT_OK);
                        BindMobileOrResetPasswordActivity.this.finish();
                        WindowUtils.getInStance().clearList();
                    }
                } else if (errCode == ResponseResult.ResultStatus.SUSPENED) {
                    ToastUtil.showToast(getString(R.string.suspenedPrompt));
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

}
